﻿/*
 * Copyright © 2020, Wuxi Safover Intelligent Technology Co., Ltd. All rights reserved.
 * 
 * 无锡安永智能科技有限公司版权所有，未经许可，不得用于商业用途
 * 
 * Visit: https://www.safover.com/ 
 */

using log4net;
using SafoverWpfFw;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using Safover.LidarCollector.Managers;
using static Safover.LidarCollector.ViewModel.DI;


namespace Safover.LidarCollector.ViewModel
{
    public class MainWindowViewModel : SfMainWindowViewModel
    {
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public MainWindowViewModel(Window window) : base(window)
        {
            SfMainTitle = "无锡安永智能科技有限公司 气溶胶激光雷达采集控制软件";
            AboutToolTip = "关于安永智能";
            CopyrightMessage = "Copyright© Wuxi Safover Technology, All Right Reserved";
            Subtitle = "by Wuxi Safover Technology Co., Ltd";
            NavigateUri = "https://www.safover.com/";
            TargetName = "";
            LogoImagePath = @"pack://application:,,,/Safover.LidarCollector.Resource;component/Images/sf128.png";
        }

        protected override void Closing(object sender, CancelEventArgs e)
        {
            if (DataCollector.Instance.IsCollectorThreadWorking)
            {
                UI.ShowMessage(new MessageBoxDialogViewModel
                {
                    Title = "提示",
                    Message = "数据采集中不能关闭系统，请先停止采集！"
                }).Wait();


                e.Cancel = true;
                return;
            }

            var tasks = new List<Task>
            {
                Task.Factory.StartNew(() => {
                    DeviceManager.DeviceFactoryInstance.CloseAll();
                }),
            };

            try
            {
                //Task.WaitAll(tasks.ToArray());
                if (!Task.WaitAll(tasks.ToArray(), TimeSpan.FromSeconds(10)))
                {
                    Environment.Exit(1);
                }
            }
            catch (AggregateException ex)
            {
                for (int j = 0; j < ex.InnerExceptions.Count; j++)
                {
                    var ie = ex.InnerExceptions[j];
                    Log.Error($"{ie.Message}", ie);
                }
            }

            e.Cancel = false;
        }

    }
}
